<?php
require_once(dirname(__FILE__).'/Abstract.php');
class Patient extends AbstractDoctorController 
{


    public function indexAction()
    {
    	$this->listingAction();
    }

    public function listingAction()
    {
    	$joinFeature = array();
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_user_role` ur', // An existing table with alias 
            'onclause' => 'ur.id_role = UserEntityORM.id_role', // 
            'select'   => '', // For select clause
        );
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN',
            'table'    => '`medic_user_role_lang` url',
            'onclause' => 'ur.id_role = url.id_role AND url.lang = \''. $this->session->userdata('lang') .'\'',
            'select'   => 'url.`name` AS role_name',
        );
        $d = $this->initListing('ORM/User/UserEntityORM', 'id_user', 'medic_user_entity', false, null, null, $joinFeature);
        
        // Get id of patient
        $d['idRoleAdmin']   = (int)$this->getConfig('idRoleAdmin');
        $d['idRoleDoctor']  = (int)$this->getConfig('idRoleDoctor');
        $d['idRolePatient'] = (int)$this->getConfig('idRolePatient');
        //debug($d);die();
        $d['title'] = $this->l('List of patients');
        $this->load->model('ORM/User/UserEntityORM');
        //$d['users'] = $this->UserEntityORM->getAllByIdRole($this->getConfig('idRolePatient'));//();

        $d['title_for_layout'] = $this->l('Patients list.');
        $d['menu'] = 'patients';
        $d['page_name'] = 'patients_list';
        
        $this->load->view('Templates/Layouts/Doctor/header', $d);
        $this->load->view('Doctor/Patient/Listing', $d);
        $this->load->view('Templates/Layouts/Doctor/footer', $d);

    }

    public function activatePatientAction()
    {
        $this->load->model('ORM/User/UserEntityORM');
        //We activate or desactivate the patient
        if ($id_user = (int)$this->input->get_post('id')) {

            $userObj = $this->UserEntityORM->getById($id_user);
            
            if ($userObj->id_user) {
                $ok = false;
                if ($this->input->get_post('act') == 'on') {
                    $userObj->activated = 2;
                    $ok = true;
                } elseif ($this->input->get_post('act') == 'off') {
                    $userObj->activated = 1;
                    $ok = true;
                }
                
                if ($ok) {
                    if ($this->UserEntityORM->save((array)$userObj)) {
                        
                        // Send the confirmation mail
                        $params = array(
                            'receiver' => $userObj->username,
                            'fromName' => $this->config->item('mail_from_name'),
                            'from'     => $this->config->item('mail_from'),
                            'subject'  => $this->l('Confirm your account'),
                            'to'       => $userObj->email,
                            
                            // Params for the view
                            
                            'connexion_link' => base_url('User/AccountService/signin/'),
                        );

                        if ($this->renderMail($params, 'ActivateAccount')) {
                            $this->session->set_flashdata('successMessage', $this->l('Patient successfully activated.'));
                        } else {
                            $this->session->set_flashdata('errorMessage', $this->l('Patient successfully activated. But the mail of information was not sent. Please contact our technical team.'));
                        }
                    } else {
                        $this->session->set_flashdata('errorMessage', $this->l('An error occured while activating. Please try again later.'));
                    }
                } else {
                    $this->session->set_flashdata('errorMessage', $this->l('An error occured. Bad HTTP request.'));
                }
            } else {
                $this->session->set_flashdata('errorMessage', $this->l('The target account was not found.'));
            }
                
        } else {
            $this->session->set_flashdata('errorMessage', $this->l('An error occured. Bad HTTP request.'));
        }
                
        redirect('Doctor/Patient/listing');
        die();
    }

    public function viewPatientAction()
    {

        $d = array();
        $d['title'] = $this->l('Patient profile');
        $d['consultations'] = $this->ConsultationMetier->getConsultations($config=array('id_patient'=>(int)$this->input->get_post('id')));
        $d['prescriptions'] = $this->ConsultationMetier->getPrescriptions($config=array('id_patient'=>(int)$this->input->get_post('id')));
        $this->load->model('ORM/User/UserEntityORM');
        $this->load->model('ORM/User/UserPatientORM');
        $d['user'] = $this->UserEntityORM->getByIdUser((int)$this->input->get_post('id'));
        $d['patient'] = $this->UserPatientORM->getByIdUser((int)$this->input->get_post('id'));
        
        $d['title_for_layout'] = $this->l('Patient profile and history.');
        $d['menu'] = 'patients';
        $d['page_name'] = 'patients_list';   
        
        $this->load->view('Templates/Layouts/Doctor/header', $d);
        $this->load->view('Doctor/Patient/ViewPatient', $d);
        $this->load->view('Templates/Layouts/Doctor/footer', $d);


    }

    public function createAction()
    {
        $d = array();
        $d['title'] = $this->l('Patient creation');
        
        // On submit
        if ($this->input->post('btn_submit') !== false){
            // Initialized the civil datas form validation
            $config = array(
                 array(
                         'field'   => 'birthday', 
                         'label'   => $this->l('Birthday'), 
                         'rules'   => 'trim|required|xss_clean'
                      ),
               array(
                     'field'   => 'phone', 
                     'label'   => $this->l('Phone'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'profession', 
                     'label'   => $this->l('Profession'), 
                     'rules'   => 'trim|xss_clean'
                  ),
               array(
                     'field'   => 'pobox', 
                     'label'   => $this->l('P.O.Box'), 
                     'rules'   => 'trim|xss_clean'
                  ),
               array(
                     'field'   => 'town', 
                     'label'   => $this->l('Town'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'nb_serur_social', 
                     'label'   => $this->l('Social security number'), 
                     'rules'   => 'trim|xss_clean'
                  ),
               array(
                     'field'   => 'address', 
                     'label'   => $this->l('Address'), 
                     'rules'   => 'trim|xss_clean'
                  ),
            
            // Initialized the signin datas form validation
            
                array(
                     'field'   => 'firstname', 
                     'label'   => $this->l('First name'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'lastname', 
                     'label'   => $this->l('Last name'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'email', 
                     'label'   => $this->l('Email'), 
                     'rules'   => 'trim|required|is_unique[medic_user_entity.email]|valid_email|xss_clean'
                  ),
               array(
                     'field'   => 'username', 
                     'label'   => $this->l('Username'), 
                     'rules'   => 'trim|required|alpha_dash|is_unique[medic_user_entity.username]|min_length[5]|xss_clean'
                  ),
            );
            $this->form_validation->set_rules($config);
            
            if ($this->form_validation->run() == FALSE){
                $this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
            } else {
                $this->load->model('ORM/User/UserEntityORM');
                $_POST['passwd'] = $this->generate_password();
                //debug($this->input->post('passwd'));die();
                // Initialize the new record
                $recordUserEntity = array(
                    'email'     => $this->input->post('email'),
                    'username'  => $this->input->post('username'),
                    'firstname' => $this->input->post('firstname'),
                    'lastname'  => $this->input->post('lastname'),
                    'passwd'    => sha1(UserEntityORM::PASSWD_PREFIX . $this->input->post('passwd')),
                    
                    // Automatic fill
                    'id_role'      => 2,                             // By default, it is a patient
                    'activated'    => 0,                             // The account is not yet activated
                    'is_connected' => 0,                             // The user is not connected
                    'token'        => md5(uniqid(rand(0, 9999))),    // Generating the token to activate the account
                    'last_activity'  => @date('Y-m-d H:i:s'),
                    'last_connexion' => null,
                    'date_add'       => @date('Y-m-d H:i:s'),
                    'date_upd'       => @date('Y-m-d H:i:s'),
                );
                // Initialize the new patient
                $recordUserPatient = array(
                    'birthday'          => $this->input->post('birthday'),
                    'phone'             => $this->input->post('phone'),
                    'profession'        => $this->input->post('profession'),
                    'pobox'             => $this->input->post('pobox'),
                    'town'              => $this->input->post('town'),
                    'nb_secur_social'   => $this->input->post('nb_secur_social'),
                    'address'           => $this->input->post('address'),
                    
                    // Automatic fill
                    'cmu'               => 0,                             // The cmu default value
                    'date_add'          => @date('Y-m-d H:i:s'),
                    'date_upd'          => @date('Y-m-d H:i:s'),
                );

                // Create the new account
                if ($user_id = $this->UserEntityORM->save($recordUserEntity)) {
                    //debug($user_id);die();
                    //$recordUserPatient['id_patient'] = $user_id;
                    $recordUserPatient['id_user'] = $user_id;
                    if (!$this->UserPatientORM->save($recordUserPatient)){
                        $this->db->delete('medic_user_entity', array('id_user' => $user_id)); 
                        $this->session->set_flashdata('errorMessage', $this->l('An error occured'));
                        redirect('Doctor/Patient/listing');
                        die();
                    } else {
                        // Send the confirmation mail
                        $params = array(
                            'receiver' => $recordUserEntity['firstname'],
                            'fromName' => $this->config->item('mail_from_name'),
                            'from'     => $this->config->item('mail_from'),
                            'subject'  => $this->l('Confirm your account'),
                            'to'       => $recordUserEntity['email'],

                            // Params for the view
                            'token'           => $recordUserEntity['token'],
                            'validation_link' => base_url('User/MyAccount/Confirmation/?username='. $recordUserEntity['username'] .'&token='.$recordUserEntity['token']),
                            'password'        => $recordUserEntity['passwd']
                        );
                        if ($this->renderMail($params, 'ConfirmSignUp')) {
                            $this->session->set_flashdata('successMessage', $this->l('Your account was successfully created. Check your mail to confirm your account.'));
                            // Redirect to the patients list
                            redirect('Doctor/Patient/listing');
                            die();
                        } else {
                            $this->session->set_flashdata('errorMessage', $this->l('Your account was successfully created. But the mail of confirmation was not sent. Please contact our technical team.'));
                        }
                    }
                     
                } else {
                    $this->session->set_flashdata('errorMessage', $this->l('An error occured while saving your patient. Please try again or contact us.'));
                }
            }
            
        }
        
        $d['title_for_layout'] = $this->l('Patient creation.');
        $d['menu'] = 'patients';
        $d['page_name'] = 'patient_creation';   
        
        $this->load->view('Templates/Layouts/Doctor/header', $d);
        $this->load->view('Doctor/Patient/CreatePatient', $d);
        $this->load->view('Templates/Layouts/Doctor/footer', $d);
    }
    
    public function editPatientAction()
    {
        $d['title_for_layout'] = $this->l('Patient edition.');
        $d['menu'] = 'patients';
        $d['page_name'] = 'patient_edition'; 
        $d['title'] = $this->l('Patient edition');
        if ($this->input->post('btn_submit') !== false){
            // Initialized the civil datas form validation
            $config = array(
                 array(
                         'field'   => 'birthday', 
                         'label'   => $this->l('Birthday'), 
                         'rules'   => 'trim|required|xss_clean'
                      ),
               array(
                     'field'   => 'phone', 
                     'label'   => $this->l('Phone'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'profession', 
                     'label'   => $this->l('Profession'), 
                     'rules'   => 'trim|xss_clean'
                  ),
               array(
                     'field'   => 'pobox', 
                     'label'   => $this->l('P.O.Box'), 
                     'rules'   => 'trim|xss_clean'
                  ),
               array(
                     'field'   => 'town', 
                     'label'   => $this->l('Town'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'nb_serur_social', 
                     'label'   => $this->l('Social security number'), 
                     'rules'   => 'trim|xss_clean'
                  ),
               array(
                     'field'   => 'address', 
                     'label'   => $this->l('Address'), 
                     'rules'   => 'trim|xss_clean'
                  ),
            
            // Initialized the signin datas form validation
            
                array(
                     'field'   => 'firstname', 
                     'label'   => $this->l('First name'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'lastname', 
                     'label'   => $this->l('Last name'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'email', 
                     'label'   => $this->l('Email'), 
                     'rules'   => 'trim|required|valid_email|xss_clean'
                  ),
               array(
                     'field'   => 'username', 
                     'label'   => $this->l('Username'), 
                     'rules'   => 'trim|required|alpha_dash|min_length[5]|xss_clean'
                  ),
            );
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run() == FALSE){
                $this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
            } else {
                // $this->load->model('ORM/User/UserEntityORM');
                $patientObj = $this->UserPatientORM->getByIdPatient((int)$this->input->get_post('id'));
                if ($patientObj->id_user){
                    // Initialize the new record
                    $recordUserEntity = array(
                        'id_user'   => $patientObj->id_user,
                        'email'     => $this->input->post('email'),
                        'username'  => $this->input->post('username'),
                        'firstname' => $this->input->post('firstname'),
                        'lastname'  => $this->input->post('lastname'),
                        
                        // Automatic fill
                        'date_upd'       => @date('Y-m-d H:i:s'),
                    );
                    // Initialize the new patient
                    $recordUserPatient = array(
                        'id_patient'        => $patientObj->id_patient,
                        'birthday'          => $this->input->post('birthday'),
                        'phone'             => $this->input->post('phone'),
                        'profession'        => $this->input->post('profession'),
                        'pobox'             => $this->input->post('pobox'),
                        'town'              => $this->input->post('town'),
                        'nb_secur_social'   => $this->input->post('nb_secur_social'),
                        'address'           => $this->input->post('address'),
                        
                        // Automatic fill
                        'date_upd'          => @date('Y-m-d H:i:s'),
                    );
                    $this->UserPatientORM->save($recordUserPatient);
                    $this->UserEntityORM->save($recordUserEntity);
                    redirect('Doctor/Patient/Listing/');
                    die();
                } else {
                    $this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
                    redirect('Doctor/Patient/editPatient/?id='.(int)$this->input->get_post('id'));
                    die();
                }
            }
        }
        $query = $this->db->select('patient.*, patient_entity.*');
        $query = $this->db->from('medic_user_patient patient');
        $query = $this->db->join('medic_user_entity patient_entity', 'patient.id_user = patient_entity.id_user');
        $query = $this->db->where('patient.id_patient', (int)$this->input->get_post('id'));
        $query = $this->db->get();
        if ($query->result()){
            $d['patient'] = $query->row(); 
        } else {
            redirect('Doctor/Patient/Listing/');
            die();
        } 

        $this->load->view('Templates/Layouts/Doctor/header', $d);
        $this->load->view('Doctor/Patient/EditPatient', $d);
        $this->load->view('Templates/Layouts/Doctor/footer', $d);
    }
    
    public function viewLogsAction()
    {   
        $this->load->model('ORM/User/UserPatientORM');
        $joinFeature = array();
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_consultation` cons', // An existing table with alias 
            'onclause' => 'cons.id_consultation = ConsultationLogORM.id_consultation', // 
            'select'   => 'cons.id_consultation, cons.id_patient, cons.id_doctor', // For select clause
        );
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_user_patient` patient', // An existing table with alias 
            'onclause' => 'cons.id_patient = patient.id_patient', // 
            'select'   => 'patient.id_user, patient.id_patient', // For select clause
        );
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_user_entity` user', // An existing table with alias 
            'onclause' => 'patient.id_user = user.id_user', // 
            'select'   => 'user.id_user, user.lastname, user.firstname', // For select clause
        );
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_user_role` ur', // An existing table with alias 
            'onclause' => 'ur.id_role = user.id_role', // 
            'select'   => '', // For select clause
        );        
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN',
            'table'    => '`medic_user_role_lang` url',
            'onclause' => 'ur.id_role = url.id_role AND url.lang = \''. $this->session->userdata('lang') .'\'',
            'select'   => 'url.`name` AS role_name',
        );
        $d = $this->initListing('ORM/Consultation/ConsultationLogORM', 'id_log', 'medic_consultation_log', false, null, null, $joinFeature);
        //debug($d);die();
        // Get id of patient
        $d['idRoleAdmin']   = (int)$this->getConfig('idRoleAdmin');
        $d['idRoleDoctor']  = (int)$this->getConfig('idRoleDoctor');
        $d['idRolePatient'] = (int)$this->getConfig('idRolePatient');
        
        $d['title'] = $this->l('Consultation logs');
        
        
        $d['title_for_layout'] = $this->l('Consultation logs.');
        $d['menu'] = 'consultations';
        $d['page_name'] = 'consultaion_logs';  
        
        $this->load->view('Templates/Layouts/Doctor/header', $d);
        $this->load->view('Doctor/Patient/ViewLogs', $d);
        $this->load->view('Templates/Layouts/Doctor/footer', $d);
    }

    public function connectedPatientsAction(){

        $d = array();
        $d['title'] = $this->l('List of connected patients');
    
        $this->load->model('ORM/User/UserEntityORM');
        $d['connected_patients'] = $this->UserEntityORM->getAllByIdRoleAndIsConnected($this->getConfig('idRolePatient'), '1');
        
        $d['title_for_layout'] = $this->l('Connected patients.');
        $d['menu'] = 'patients';
        $d['page_name'] = 'connected_patients';
        
        $this->load->view('Templates/Layouts/Doctor/header', $d);
        $this->load->view('Doctor/Patient/ConnectedPatients', $d);
        $this->load->view('Templates/Layouts/Doctor/footer', $d);

   
    }

    public function exportListOfPatientsAction()
    {
        
    }

    protected function generate_password( $length = 8 ) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?";
        $password = substr( str_shuffle( $chars ), 0, $length );
        return $password;
    }
}

